package com.ruoyi.websocket.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.websocket.config.INettyConfig;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
    private INettyConfig iNettyConfig;
    public HeartbeatHandler() {
        iNettyConfig = SpringUtil.getBean(INettyConfig.class);
    }

    public HeartbeatHandler(INettyConfig iNettyConfig) {
        this.iNettyConfig = iNettyConfig;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;

            if (event.state() == IdleState.READER_IDLE) {
                // 读空闲（30秒内没有收到任何消息）
                log.warn("客户端 {} ,{}秒内无活动，即将断开连接", ctx.channel().remoteAddress(), iNettyConfig.getReaderIdleTime());

                // 发送关闭帧并关闭连接
                CloseWebSocketFrame closeFrame = new CloseWebSocketFrame(
                        1000, // NORMAL_CLOSURE - 正常关闭
                        "Connection closed due to inactivity"
                );
                ctx.writeAndFlush(closeFrame).addListener(ChannelFutureListener.CLOSE);

                // 或者直接关闭连接
                // ctx.close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接已关闭: {}", ctx.channel().remoteAddress());
        super.channelInactive(ctx);
    }
}
